###############################################################################
# Plot 3
###############################################################################
# This Script contains the code to build the first figure
###############################################################################
# Content
###############################################################################
# 1) Dependencies
# 2) Load Data
# 3) Aggregation for Fig. 1
# 4) Fig. 1
###############################################################################
# 1) Dependencies
###############################################################################
library(readr)
library(dplyr)
library(ggplot2)
library(gganimate)
library(ggeffects)
library(ggExtra)
library(ggridges)
library(ggrepel)
library(ggpubr)
library(grid)
library(scales)
library(lubridate)
library(extrafont)
library(reshape2)
library(here)
library(ggforce)
library(png)
library(readxl)
library(grid)
library(gridExtra)
library(ggpubr)
library(ggalt)
library(stringr)
###############################################################################
# 2) Load Data
###############################################################################
# Set Path
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
rm(list=ls())

# Custom functions
# ggplot rescale x axis....
scale_x_reordered <- function(..., sep = "___") {
  reg <- paste0(sep, ".+$")
  ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}
# ggplot order over facets...
reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

suppressWarnings(source('ggplot_theme_ddl.R', encoding = "UTF-8"))

# Load Data
df <- readRDS("../data/smd_ner_2015_2019_combined.RDS")
candidates_list_15 <- read.csv('../support/candidates-2015/00-Named_Entity_List_withID.csv', stringsAsFactors = F) %>% 
  as_tibble %>% mutate(id=as.character(id))
candidates_list_19 <- read.csv('../support/candidates-2019/00-Named_Entity_List_withID.csv', stringsAsFactors = F) %>% 
  as_tibble %>% mutate(id=as.character(id))

candidates_list_19 <- candidates_list_19 %>% mutate(candidacy = as.character(gsub("\\s", " ", council))) %>% 
  mutate(council = case_when(candidacy %in% c("SR", "Former Staenderat", "Former Staenderat") ~ "sr",
                             candidacy %in% c("NR", "Former Nationalrat", "Former Nationalrat") ~  "nr",
                             candidacy %in% c("SR und NR", "NR und SR") ~ "sr & nr")) %>% 
  dplyr::select(-c(candidacy))

df$year <- as.character(df$year)
df$date <- format(as.Date(df$date, "%m-%d"), format = "%m-%d")
df$fullname <- ifelse(df$fullname == "Adèle Goumaz", "Adèle Thorens Goumaz", df$fullname)
df$fullname <- ifelse(df$fullname == "Niklaus-Samuel Gugger", "Nik Gugger", df$fullname)
df$incumbent <- ifelse(df$fullname == "Philipp Müller", 1, df$incumbent)

# Remove Federal Councilors
council <- TRUE
# Remove Party Presidents
president <- TRUE

# Council members 2015
council_15 <- c("Ueli Maurer", "Alain Berset", "Didier Burkhalter",
                "Simonetta Sommaruga", "Eveline Widmer Schlumpf",
                "Johann Schneider-Ammann", "Doris Leuthard")

# Council members 2019
council_19 <- c("Ueli Maurer", "Alain Berset", "Ignazio Cassis",
                "Simonetta Sommaruga", "Guy Parmelin",
                "Karin Keller-Sutter", "Viola Amherd")

# Party Presidents 2015
presi_15 <- c("Toni Brunner", "Christian Levrat", "Philipp Müller",
              "Christophe Darbellay", "Regula Rytz", "Martin Bäumle", "Martin Landolt")

# Party Presidents 2019
presi_19 <- c("Albert Rösti", "Christian Levrat", "Petra Gössi",
              "Gerhard Pfister", "Regula Rytz", "Jürg Grossen", "Martin Landolt")


# Remove Council Members:
if(council == T){
  df <- df %>% dplyr::filter((year == "2015" & !fullname %in% council_15) |
                               (year == "2019" & !fullname %in% council_19))
}
# Remove Party Presidents:
if(president == T){
  df <- df %>% dplyr::filter((year == "2015" & !fullname %in% presi_15) |
                               (year == "2019" & !fullname %in% presi_19))
}
###############################################################################
#3) Aggregation for Fig. 3
###############################################################################
names(df)

df$n_candidates_on_list <- ifelse(df$year == "2019", 3599, 2888)

df <- df %>% dplyr::mutate(n_candidates_on_list = case_when(year == "2019" & incumbent == 1 ~ 186,
                                                     year == "2019" & incumbent == 0 ~ 3599,
                                                     year == "2015" & incumbent == 1 ~ 200,
                                                     year == "2015" & incumbent == 0 ~ 2888
))

agg1 <- df %>% dplyr::group_by(year, incumbent, gender, n_candidates_on_list, fullname, person.id) %>%
               dplyr::summarise(n = n()) %>% dplyr::filter(!is.na(fullname) == T)

helper <- dplyr::filter(agg1, year == "2015")
candidates_list_15 <- candidates_list_15 %>% filter(!id %in% helper$person.id)

helper <- dplyr::filter(agg1, year == "2019")
candidates_list_19 <- candidates_list_19 %>% filter(!id %in% helper$person.id)

candidates_list_15 <- candidates_list_15 %>% dplyr::select(c(fullname,gender,incumbent,id)) %>% 
  dplyr::mutate(person.id = id,
                n = 0,
                year = "2015") %>% 
  dplyr::select(-c("id"))

candidates_list_19 <- candidates_list_19 %>% dplyr::select(c(fullname,gender,incumbent,id)) %>% 
  dplyr::mutate(person.id = id,
                n = 0,
                year = "2019") %>% 
  dplyr::select(-c("id"))

df <- df %>% dplyr::mutate(list_place_1 = ifelse(!is.na(list_place_1) == T, list_place_1,
                                                 ifelse(council %in% c("sr", ""), 1,
                                                        ifelse(council == "nr", 1, NA)))) %>%
  dplyr::mutate(list_place_top = ifelse(list_place_1 <= 5, "Top Place", "Bottom Place"))

agg3 <- df %>% dplyr::group_by(year,date,gender,selectsclass) %>% dplyr::summarise(n = n()) %>% ungroup %>%
  dplyr::filter(gender %in% c('m','f')) %>%
  dplyr::group_by(year,date,selectsclass) %>% 
  dplyr::mutate(n_tot = sum(n)) %>%
  dplyr::mutate(freq = n/n_tot) %>%
  dplyr::mutate(after_strike = ifelse(as.Date(paste0(year,"-",date)) > as.Date("2019-06-14"), 1, 0))

agg3a <- df %>% dplyr::group_by(year,date,gender) %>% dplyr::summarise(n = n()) %>%  ungroup %>%
  dplyr::filter(gender %in% c('m','f')) %>%
  dplyr::group_by(year,date) %>% 
  dplyr::mutate(n_tot = sum(n)) %>%
  dplyr::mutate(freq = n/n_tot) %>%
  dplyr::mutate(after_strike = ifelse(as.Date(paste0(year,"-",date)) > as.Date("2019-06-14"), 1, 0)) %>%
  dplyr::mutate(selectsclass = "All Together")

agg3a <- agg3a %>% ungroup %>% dplyr::group_by(year, gender, selectsclass) %>% tidyr::complete(date = unique(df$date), fill = list(n = 0,
                                                                                                                            freq = 0,
                                                                                                                            n_tot = NA))


agg3 <- agg3 %>% dplyr::filter(selectsclass == "GenderIssues_Discrimination")

agg3 <- agg3 %>% ungroup %>% dplyr::group_by(year, gender, selectsclass) %>% tidyr::complete(date = unique(df$date), fill = list(n = 0,
                                                                                                                          freq = 0,
                                                                                                                          n_tot = NA))

agg3a <- agg3a %>%dplyr:: mutate(after_strike = ifelse(as.Date(paste0(year,"-",date)) > as.Date("2019-06-14"), 1, 0))
agg3 <- agg3 %>% dplyr::mutate(after_strike = ifelse(as.Date(paste0(year,"-",date)) > as.Date("2019-06-14"), 1, 0))

agg3 <- dplyr::bind_rows(agg3, agg3a) %>% filter(gender == "f") %>% dplyr::mutate(date = as.Date(date, format = ("%m-%d"))) %>%
  dplyr::mutate(selectsclass = case_when(selectsclass == "GenderIssues_Discrimination" ~ "Newspaper Articles with Topic Gender",
                                         selectsclass == "All Together" ~ "All Newspaper Articles"))

labeldat = data.frame(selectsclass = c("All Newspaper Articles", "Newspaper Articles with Topic Gender"),
                      x = c(as.Date("2024-06-14"), as.Date("2024-06-14")),
                      y = c(.25, .5),
                      label = c("Women's Strike", "Women's Strike"))
###############################################################################
# 4) Fig. 3
###############################################################################
# Values for colors
values_year <- c("2019" = "#DD2461", "2015" = "#7D7D7C")

f3 <- ggplot(agg3, aes(y = freq, x=date, color = year)) +
  geom_smooth(aes(y = freq, x=date, color = year), filter(agg3, after_strike == 0), inherit.aes = F, formula = "y ~ x",method = "loess", se = F, n = 7000, span = .45, size = .85) +
  geom_smooth(aes(y = freq, x=date, color = year), filter(agg3, after_strike == 1), inherit.aes = F, formula = "y ~ x",method = "loess", se = F, n = 1000, span = .45, size = .85) +
  #geom_point(size = .2, alpha = .2) +
  geom_vline(xintercept = (as.Date("2024-06-14")), color = "grey", linewidth = 1.25) +
  geom_text(data = labeldat, mapping = aes(x = x-3.5, y = y, label = label), angle = 90, size = 7.5, color = "black", inherit.aes = F) +
  scale_x_date(breaks = "2 month", labels = date_format("%b"), expand = c(0, 0)) +
  scale_y_continuous(labels = scales::percent_format(accuracy=1)) +
  facet_wrap(~selectsclass, ncol = 1, scales = "free_y") +
  ddl_theme() +
  labs(title = '',
       y = 'Share of Mentions', x = 'Days', color = "Year:") +
  scale_color_manual(name="Year", values = values_year, labels = c("2015", "2019")) +
  theme(legend.position = "bottom", legend.direction = "horizontal",
        strip.background = element_blank(), strip.text = element_text(color = "black"),
        axis.text.x = element_text(angle = 0, hjust = .5, vjust = 1, size = 20),
        axis.text.y = element_text(hjust=.5, size = 20),
        strip.text.x = element_text(size = 20),
        axis.title = element_text(size = 20),
        plot.title = element_text(size = 24),
        legend.text = element_text(size = 20),
        legend.title = element_text(size =20),
        plot.margin = unit(c(.5,1.3,.5,.5), "cm"),
        legend.key.size = unit(1.5,"line"),
        axis.line.x = element_line(color="black", size = .5),
        axis.line.y = element_line(color="black", size = .5),
        panel.spacing.x=unit(2.5, "lines"))

f3

ggsave(plot = f3, filename='../img_main/figure_3.png',width=16, height=12, dpi = 300, bg = "white")
